package com.ruoyi.client.runjianhr.service.Impl;

import com.ruoyi.client.runjianhr.constants.RunjianHRAPIUtils;
import com.ruoyi.client.runjianhr.service.UtilService;
import com.ruoyi.client.runjianhr.bean.ResultToken;
import com.alibaba.fastjson.JSON;
import com.github.kevinsawicki.http.HttpRequest;
import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 获取润建token 接口
 */
@Service
public class UtilServiceImpl implements UtilService {

    @Resource
    RedisCache redisCache;

    /**
     * 获取润建token
     * @param map { "username":"admin",
     *              "password": "123456",
     *              "clientId": "mvc",
     *              "clientSerect":"123"  }
     * @return 返回token
     */
    @Override
    public String getToken(Map<String, String> map) {
        /*if(map.size()==0){
            return "参数不能为空!";
        }*/
        //先固定这些
        map.put("username","admin");
        map.put("password","123456");
        map.put( "clientId", "mvc");
        map.put("clientSerect","123");
        //获取redis 中的token
        Object object = redisCache.getCacheObject("token");
        if(object != null){
            return redisCache.getCacheObject("token");
        }
        try {
            //调用接口获取 token 数据
            String result = HttpRequest.post(RunjianHRAPIUtils.accessTokenUrl)
                    .accept("application/json; charset=utf-8")
                    .contentType("application/json; charset=utf-8")
                    .send(JSON.toJSON(map).toString())
                    .body();
            //返回结果
            ResultToken resultToken = JSON.parseObject(result,ResultToken.class);
            //获取token
            String token = resultToken.getCustom().getAccess_token();
            //获取token有效时间
            int expires = resultToken.getCustom().getExpires_in();
            //设置token有效时间到redis缓存中
            redisCache.setCacheObject("token",token,expires-60, TimeUnit.SECONDS);
            return token;
        }catch (Exception e){
            e.printStackTrace();
            return e.getMessage();
        }

    }
}
